<?php
namespace app\common\service;
use think\facade\Log;
class NotionMifiHandler
{
    /**
     * 处理上行主题消息
     * @param string $topic MQTT主题
     * @param string $message JSON消息
     * @return array 解析后的数据
     */
    public function handleUpTopic($topic, $message)
    {
        
        $topicParts = explode('/', $topic);
        
        $imei = $topicParts[2] ?? '';
        $action = $topicParts[3] ?? '';
       
        //$data = json_decode($message, true);
        $data = $message;
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception("Invalid JSON format");
        }
        
        $result = [
            'imei' => $imei,
            'action' => $action,
            'data' => $data
        ];
        
        Log::info("result为: ". json_encode($result,JSON_UNESCAPED_UNICODE));
        switch ($action) {
            case 'report':
                return $this->handleReportMessage($result);
            case 'set_reply':
                return $this->handleSetReplyMessage($result);
            case 'get_reply':
                return $this->handleGetReplyMessage($result);
            default:
                throw new \Exception("Unknown action: {$action}");
        }
    }
    
    /**
     * 处理下行主题消息
     * @param string $topic MQTT主题
     * @param string $message JSON消息
     * @return array 解析后的数据
     */
    public function handleDownTopic($topic, $message)
    {
        $topicParts = explode('/', $topic);
        $imei = $topicParts[2] ?? '';
        $action = $topicParts[4] ?? '';
        
        $data = json_decode($message, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception("Invalid JSON format");
        }
        
        $result = [
            'imei' => $imei,
            'action' => $action,
            'data' => $data
        ];
        
        switch ($action) {
            case 'set':
                return $this->handleSetCommand($result);
            case 'get':
                return $this->handleGetCommand($result);
            default:
                throw new \Exception("Unknown action: {$action}");
        }
    }
    
    /**
     * 处理设备上报基本属性
     * @param array $messageData
     * @return array
     */
    protected function handleReportMessage($messageData)
    {
        $requiredFields = ['imei', 'timestamp'];
        
        /*foreach ($requiredFields as $field) {
            if (empty($messageData['data'][$field])) {
                throw new \Exception("Missing required field: {$field}");
            }
        }*/
        
        // 验证IMEI格式
        if (!preg_match('/^\d{15}$/', $messageData['imei'])) {
            throw new \Exception("Invalid IMEI format");
        }
         
        // 处理多SIM卡信息
        if (isset($messageData['data']['multi_sim'])) {
            $messageData['data']['multi_sim'] = $this->processMultiSimData($messageData['data']['multi_sim']);
        }
        /*echo '<pre>';
        print_r($messageData);
        echo '<pre/>';exit;*/
       
        return $messageData;
    }
    
    /**
     * 处理设备上报指令执行结果
     * @param array $messageData
     * @return array
     */
    protected function handleSetReplyMessage($messageData)
    {
        $requiredFields = ['imei', 'timestamp', 'uuid', 'result_list'];
        /*foreach ($requiredFields as $field) {
            if (empty($messageData['data'][$field])) {
                throw new \Exception("Missing required field: {$field}");
            }
        }*/
        
        // 验证result_list格式
        if (!is_array($messageData['data']['result_list'])) {
            throw new \Exception("result_list should be an array");
        }
        
        return $messageData;
    }
    
    /**
     * 处理设备上报指定属性
     * @param array $messageData
     * @return array
     */
    protected function handleGetReplyMessage($messageData)
    {
        $requiredFields = ['imei', 'timestamp'];
        /*foreach ($requiredFields as $field) {
            if (empty($messageData['data'][$field])) {
                throw new \Exception("Missing required field: {$field}");
            }
        }
        */
        if (!isset($messageData['data']['data']) || !is_array($messageData['data']['data'])) {
            throw new \Exception("Missing or invalid data field");
        }
        
        return $messageData;
    }
    
    /**
     * 处理服务器下发指令
     * @param array $messageData
     * @return array
     */
    protected function handleSetCommand($messageData)
    {
        $requiredFields = ['uuid', 't'];
        /*foreach ($requiredFields as $field) {
            if (empty($messageData['data'][$field])) {
                throw new \Exception("Missing required field: {$field}");
            }
        }*/
        
        if (!isset($messageData['data']['data']) || !is_array($messageData['data']['data'])) {
            throw new \Exception("Missing or invalid data field");
        }
        
        // 验证时间格式
        if (!preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $messageData['data']['t'])) {
            throw new \Exception("Invalid time format");
        }
        
        return $messageData;
    }
    
    /**
     * 处理服务器获取指定属性指令
     * @param array $messageData
     * @return array
     */
    protected function handleGetCommand($messageData)
    {
        $requiredFields = ['uuid', 't'];
        /*foreach ($requiredFields as $field) {
            if (empty($messageData['data'][$field])) {
                throw new \Exception("Missing required field: {$field}");
            }
        }*/
        
        if (!isset($messageData['data']['data']) || !is_array($messageData['data']['data'])) {
            throw new \Exception("Missing or invalid data field");
        }
        
        return $messageData;
    }
    
    /**
     * 处理多SIM卡数据
     * @param array $multiSimData
     * @return array
     */
    protected function processMultiSimData($multiSimData)
    {
        if (!isset($multiSimData['sim_list']) || !is_array($multiSimData['sim_list'])) {
            throw new \Exception("Invalid sim_list format");
        }
        
        // 验证SIM卡列表
        foreach ($multiSimData['sim_list'] as $sim) {
            if (!isset($sim['sim_id']) || !in_array($sim['sim_id'], ['0', '1', '2'])) {
                throw new \Exception("Invalid sim_id in sim_list");
            }
        }
        
        return $multiSimData;
    }
    
    /**
     * 构建下行指令
     * @param string $imei 设备IMEI
     * @param string $action set或get
     * @param array $data 指令数据
     * @return array 包含topic和message的数组
     */
    public function buildDownCommand($imei, $action, $data)
    {
        if (!in_array($action, ['set', 'get'])) {
            throw new \Exception("Invalid action, must be 'set' or 'get'");
        }
        
        if (!preg_match('/^\d{15}$/', $imei)) {
            throw new \Exception("Invalid IMEI format");
        }
        
        $message = [
            'uuid' => $this->generateUuid(),
            't' => date('Y-m-d H:i:s'),
            'data' => $data
        ];
        
        return [
            'topic' => "notion/down/{$imei}/{$action}",
            'message' => json_encode($message, JSON_UNESCAPED_UNICODE)
        ];
    }
    
    /**
     * 生成UUID
     * @return string
     */
    protected function generateUuid()
    {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
}